package com.sunrise.controller;

import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.sunrise.pojo.system.DingTalk;
import com.sunrise.service.DingTalkService;
import com.sunrise.util.DateUtil;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import result.GraceJSONResult;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @Author: liansen
 * @Date: 2024-04-27  17:05
 */
@RestController
@RequestMapping("/ding")
public class DingTalkController {

    @Resource
    private DingTalkService dingTalkService;

    @PostMapping("/saveDingTalk")
    public GraceJSONResult saveDingTalk() {

        //钉钉打卡之后收到的json
        String jsonStr = "{\"DataList\":[{\"address\":\"陕西省西安市未央区汉城街道德克士(北客站餐厅)西安北站\"," +
                "\"checkTime\":1714131343000,\"corpId\":\"ding7bf00be376bca10ff2c783f7214b6d69\",\"locationResult\":\"Normal\"," +
                "\"groupId\":\"AF6858B41B5FE5C6D829194FF93429BB\",\"latitude\":34.374373," +
                "\"bizId\":\"0D0BE37807C93F1967906C8441F96434\",\"locationMethod\":\"MAP\"," +
                "\"checkByUser\":true,\"userId\":\"313513560021441973\"," +
                "\"longitude\":108.938362}],\"eventId\":\"85439a1583294bac9bf4939a7f9df36c\"," +
                "\"EventType\":\"attendance_check_record\"}";

        //转为JSONObject类型 Hutool包
        JSONObject eventJson = JSONUtil.parseObj(jsonStr);
        JSONArray jsonArray = JSONUtil.parseArray(eventJson.get("DataList").toString());
        List<DingTalk> dtoList = jsonArray.stream().map(data -> (JSONObject) data).map(data -> {
            DingTalk dto = new DingTalk();
            //这里不能使用BeanUtils.copyProperties(), 因为data是JSONObject类型, 并不是一个具体的类型, 无法使用get属性
            dto.setAddress(data.getStr("address"));
            dto.setUserId(data.getStr("userId"));
            LocalDateTime checkTime = DateUtil.convertTimestamp(data.getLong("checkTime"));
            dto.setCheckTime(checkTime);
            return dto;
        }).collect(Collectors.toList());
        dingTalkService.saveBatch(dtoList);
        return GraceJSONResult.ok();
    }
}
